package com.wing.user.controller.admin;

import chat.qiye.wechat.sdk.api.message.resp.AppMessageSendResp;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.enterprisecab.product.model.response.EnterpriseVO;
import com.wing.user.model.entity.*;
import com.wing.user.model.response.EnterpriseInfoVO;
import com.wing.user.model.response.UserAuthVO;
import com.wing.user.model.response.UserVO;
import com.wing.user.service.*;
import com.wing.user.utils.ExcelUtils;
import com.wing.common.utils.RSAUtils;
import com.wing.web.excel.*;
import com.wing.web.utils.JwtUtils;
import com.wing.wecom.service.MessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author
 */
@Slf4j
@Validated
@Api(value = "Admin-用户管理", tags = "#/user/user")
@RestController
@RequestMapping("/user/admin/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    private final DepartmentService departmentService;
    private final CompanyInfoService companyInfoService;
    private final RoleService roleService;
    private final UserRoleService userRoleService;
    private final RoleMenuService roleMenuService;
    private final PasswordEncoder passwordEncoder;

    @Resource
    PositionService positionService;

    private static Long departmentId = null;

    @ApiOperation(value = "查询所有用户", notes = "搜索")
    @ApiImplicitParams({@ApiImplicitParam(name = "page", value = "第几页", example = "1", required = true, dataType = "Integer", paramType = "query"), @ApiImplicitParam(name = "limit", value = "每页多少条", example = "10", required = true, dataType = "Integer", paramType = "query"), @ApiImplicitParam(name = "searchKey", value = "筛选条件字段", example = "phone", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "searchValue", value = "筛选条件关键字", example = "13888888888", dataType = "String", paramType = "query")})
    @GetMapping("/list")
    public PageResult<User> list(Integer page, Integer limit, String searchKey, String searchValue, Long departmentId, Long postId, String username, String nickname, String phone, String idCard, String enterpriseCode, Long roleId, String isJob) {
        if (page == null) {
            page = 1;
        }
        if (limit == null) {
            limit = 10;
        }
        Page<User> userPage = new Page<>(page, limit);
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.ne("id", 519906343969112064l);
        if (searchKey != null && !searchKey.trim().isEmpty() && searchValue != null && !searchValue.trim().isEmpty()) {
            wrapper.eq(searchKey, searchValue);
        }
        wrapper.orderBy(true, false, "create_time");
        if (null != departmentId) {
            wrapper.eq("department_id", departmentId);
        }
        if (null != postId) {
            wrapper.eq("post_id", postId);
        }
        if (StringUtils.isNotBlank(username)) {
            wrapper.like("username", "%" + username + "%");
        }
        if (StringUtils.isNotBlank(nickname)) {
            wrapper.like("nickname", "%" + nickname + "%");
        }
        if (StringUtils.isNotBlank(phone)) {
            wrapper.like("phone", "%" + phone + "%");
        }
        if (StringUtils.isNotBlank(idCard)) {
            wrapper.like("id_card", "%" + idCard + "%");
        }
        Map paramMap = new HashMap();
        paramMap.put("departmentId", departmentId);
        paramMap.put("postId", postId);
        paramMap.put("username", username);
        paramMap.put("nickname", nickname);
        paramMap.put("phone", phone);
        paramMap.put("idCard", idCard);
        if (StringUtils.isNotBlank(enterpriseCode)) {
            paramMap.put("enterpriseCode", enterpriseCode);
        }
        paramMap.put("roleId", roleId);
        if (StringUtils.isNotBlank(isJob)) {
            paramMap.put("isJob", User.IsJob.valueOf(isJob).getValue());
        }
        this.departmentId = JwtUtils.getEnterpriseId();
        Page<User> pageList = userService.pageList(userPage, paramMap);
//        List<User> userList = userPage.getRecords();
        List<User> userList = pageList.getRecords();
        if (userList.size() > 0) {
            // 关联查询role
            List<Long> userIds = new ArrayList<>();
            for (User one : userList) {
                userIds.add(one.getId());
            }
            List<UserRole> userRoles = userRoleService.list(new QueryWrapper<UserRole>().in("user_id", userIds));
            List<Role> roles = roleService.list(null);
            for (User one : userList) {
                List<Role> tempUrs = new ArrayList<>();
                for (UserRole ur : userRoles) {
                    if (one.getId().equals(ur.getUserId())) {
                        for (Role r : roles) {
                            if (ur.getRoleId().equals(r.getId())) {
                                tempUrs.add(r);
                            }
                        }
                    }
                }

                one.setRoles(tempUrs);
            }
        }
        //关联相关业务属性
//        userList.parallelStream().forEach(k -> {
//            log.info("关联相关业务属性查询开始: companyInfoId = " + k.getCompanyInfoId());
//            // 企业
//            CompanyInfo companyInfo = companyInfoService.getById(k.getCompanyInfoId());
//            if(companyInfo != null){
//                k.setCompanyInfoName(companyInfo.getName());
//            }
//
//            log.info("关联相关业务属性查询开始: departmentId = " + k.getDepartmentId());
//            // 部门
//            Department department = departmentService.getById(k.getDepartmentId());
//            if(department != null){
//                k.setDepartmentName(department.getName());
//            }
//        });
        return new PageResult<>(userList, pageList.getTotal());
    }

    @ApiOperation(value = "查询用户", notes = "搜索")
    @ApiImplicitParams({@ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String", paramType = "form")})
    @GetMapping("/getByUsername")
    public JsonResult<UserAuthVO> getByUsername(String username) {
        UserAuthVO user = userService.getByUsername(username);
        return JsonResult.success(user);
    }

    @ApiOperation(value = "查询用户", notes = "搜索")
    @ApiImplicitParams({@ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "form")})
    @GetMapping("/getByPhone")
    public JsonResult<UserAuthVO> getByPhone(String phone) {
        UserAuthVO user = userService.getByPhone(phone);
        return JsonResult.success(user);
    }


    @ApiOperation(value = "查询用户", notes = "搜索")
    @ApiImplicitParams({@ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "form")})
    @GetMapping("/getBy/{departmentId}")
    public List<User> getBy(@PathVariable("departmentId") Long departmentId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("department_id", departmentId);
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.orderByDesc("create_time");
        List<User> list = this.userService.list(queryWrapper);
        return list;
    }

    @ApiOperation(value = "查询用户", notes = "搜索")
    @ApiImplicitParams({@ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "form")})
    @GetMapping("/getByOpenId")
    public JsonResult<UserAuthVO> getByOpenId(String openId) {
        UserAuthVO user = userService.getByOpenId(openId);
        return JsonResult.success(user);
    }

    @ApiOperation(value = "添加用户", notes = "添加")
    @ApiImplicitParams({@ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "User", paramType = "form"), @ApiImplicitParam(name = "roleIds", value = "用户角色id，多个用','分割", required = true, dataType = "String", paramType = "form")})
    @PostMapping("/add")
    public JsonResult add(User user, String roleIds) {
        try {
            JsonResult jsonResult = userService.addUser(user, roleIds.split(","));
            return jsonResult;
        } catch (BusinessException e) {
            log.error("add user fail", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("add user fail", e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "添加用户", notes = "添加")
    @ApiImplicitParams({@ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "User", paramType = "form"), @ApiImplicitParam(name = "roleIds", value = "用户角色id，多个用','分割", required = true, dataType = "String", paramType = "form")})
    @PostMapping("/addUser")
    public JsonResult addUser(@RequestBody User user) {
        try {
            JsonResult jsonResult = userService.addUser(user, user.getRoleIds().split(","));
            return jsonResult;
        } catch (BusinessException e) {
            log.error("add user fail", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("add user fail", e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "修改用户角色", notes = "修改")
    @ApiImplicitParams({@ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "User", paramType = "form"), @ApiImplicitParam(name = "roleIds", value = "用户角色id", required = true, dataType = "String", paramType = "form")})
    @PutMapping("/updateUser")
    public JsonResult updateUser(@RequestBody User user) {
        try {
            JsonResult jsonResult = userService.update(user, user.getRoleIds().split(","));
            return jsonResult;
        } catch (BusinessException e) {
            log.error("update user fail", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("update user fail", e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "修改用户角色", notes = "修改")
    @ApiImplicitParams({@ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "User", paramType = "form"), @ApiImplicitParam(name = "roleIds", value = "用户角色id", required = true, dataType = "String", paramType = "form")})
    @PutMapping("/update")
    public JsonResult update(User user, String roleIds) {
        try {
            JsonResult jsonResult = userService.update(user, roleIds.split(","));
            return jsonResult;
        } catch (BusinessException e) {
            log.error("update user fail", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("update user fail", e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "修改用户状态", notes = "修改状态")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "form"), @ApiImplicitParam(name = "state", value = "状态：0正常，1冻结", required = true, dataType = "Integer", paramType = "form")})
    @PutMapping("/updateStatus")
    public JsonResult updateStatus(Long userId, Integer status) {
        if (status == null || (status != 0 && status != 1)) {
            return JsonResult.fail("state值需要在[0,1]中");
        }
        User user = new User();
        user.setId(userId);
        user.setStatus(status);
        if (userService.updateById(user)) {
            return JsonResult.success();
        }
        return JsonResult.fail();
    }

    @ApiOperation(value = "重置密码", notes = "重置密码")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "path")})
    @PutMapping("/resetPassword")
    public JsonResult resetPassword(Long id) {
        User user = new User();
        user.setId(id);
        user.setPassword(passwordEncoder.encode(DigestUtil.md5Hex("123456")));
        try {
            // 加密
            String passwordRsa = RSAUtils.encryptByPublicKey(RSAUtils.publicKey, DigestUtil.md5Hex("123456"));
            user.setPasswordRsa(passwordRsa);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (userService.updateById(user)) {
            return JsonResult.success("重置密码成功");
        }
        return JsonResult.fail("重置密码失败");
    }

    @ApiOperation(value = "删除用户", notes = "删除")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "path")})
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long userId) {
        try {
            JsonResult jsonResult = userService.delete(userId);
            return jsonResult;
        } catch (BusinessException e) {
            log.error("del user fail", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("del user fail", e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "添加角色菜单", notes = "权限")
    @PostMapping("/addRoleMenu")
    public JsonResult addRoleMenu(@RequestBody List<RoleMenu> roleMenuList) {
        if (roleMenuService.add(roleMenuList)) {
            return JsonResult.success("保存成功");
        }
        return JsonResult.fail("保存失败");
    }

    /**
     * 查看当前用户
     */
    @GetMapping("/showInfo")
    public JsonResult showUpInfo() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        String userId = String.valueOf(JwtUtils.getLoginUserId());
        queryWrapper.eq("id", userId);
        User user = userService.getOne(queryWrapper);
        List<Long> list = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getId()).select(UserRole::getRoleId)).stream().map(UserRole::getRoleId).collect(Collectors.toList());
        String result = list.stream()
                .filter(Objects::nonNull)  // 过滤掉 null
                .map(String::valueOf)
                .collect(Collectors.joining(","));
        user.setRoleIds(result);

        return JsonResult.success(user);
    }

    @ApiOperation(value = "检查唯一性")
    @ApiImplicitParams({@ApiImplicitParam(name = "username", value = "工号", required = false, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "phone", value = "手机号", required = false, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "Long", paramType = "query")})
    @GetMapping("/isOnly")
    public JsonResult isOnly(@RequestParam(name = "username", required = false) String username, @RequestParam(name = "phone", required = false) String phone, @RequestParam(name = "id", required = false) Long id) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.eq("username", username);
        }
        if (StringUtils.isNotBlank(phone)) {
            queryWrapper.eq("phone", phone);
        }
        if (id != null) {
            queryWrapper.ne("id", id);
        }
        int count = userService.count(queryWrapper);
        return JsonResult.success(count == 0);
    }

    /**
     * 根据用户id返回用户信息
     */
    @GetMapping("/getUserInfo")
    public JsonResult<UserVO> getUserInfo(@RequestParam("id") Long id) {
        User user = userService.getById(id);
        return JsonResult.success(user);
    }

    /**
     * 查询所有用户
     */
    @GetMapping("/getAll")
    public JsonResult getAll() {
        List<User> list = userService.list();
        return JsonResult.success(list);
    }

    @ApiOperation(value = "修改柜子面板权限", notes = "修改柜子面板权限")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "form"), @ApiImplicitParam(name = "hasSettingRole", value = "是否拥有柜子面板的设置权限", required = true, dataType = "Boolean", paramType = "form")})
    @PutMapping("/updateHasSettingRole")
    public JsonResult updateHasSettingRole(Long userId, Boolean hasSettingRole) {
        if (hasSettingRole == null) {
            return JsonResult.fail("参数错误");
        }
        User user = new User();
        user.setId(userId);
        user.setHasSettingRole(hasSettingRole);
        if (userService.updateById(user)) {
            return JsonResult.success();
        }
        return JsonResult.fail();
    }

    @ApiOperation(value = "修改柜子面板权限", notes = "修改柜子面板权限")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "form"), @ApiImplicitParam(name = "hasSettingRole", value = "是否拥有柜子面板的设置权限", required = true, dataType = "Boolean", paramType = "form")})
    @PutMapping("/updateHasWcabSettingRole")
    public JsonResult updateHasWcabSettingRole(Long userId, Boolean hasWcabSettingRole) {
        if (hasWcabSettingRole == null) {
            return JsonResult.fail("参数错误");
        }
        User user = new User();
        user.setId(userId);
        user.setHasWcabSettingRole(hasWcabSettingRole);
        if (userService.updateById(user)) {
            return JsonResult.success();
        }
        return JsonResult.fail();
    }

    /**
     * 根据用户id查询电话、部门、岗位
     */
    @GetMapping("/getUserInfoByUserId")
    public JsonResult<UserVO> getUserInfoByUserId(Long userId) {
        UserVO userVO = userService.getUserInfoByUserId(userId);
        return JsonResult.success(userVO);
    }

    /**
     * 根据岗位id查询用户
     */
    @GetMapping("/getUserByPostId")
    public JsonResult getUserByPostId(Long postId) {
        List<User> userList = userService.list(new LambdaQueryWrapper<User>().eq(User::getPostId, postId));
        return JsonResult.success(userList);
    }

    /**
     * 通过用户名或昵称找到用户
     *
     * @param name 用户名或昵称
     * @return {@link UserAuthVO}
     */
    @GetMapping(value = "/getByName", params = "name")
    JsonResult<UserVO> findUserByName(@RequestParam("name") String name) {
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("username",name).or().eq("nickname",name);
//        List<User> list = userService.list(queryWrapper);
//        //利用json 实现list 拆包解包
//        List<UserVO> userVOS = JSON.parseObject(JSON.toJSONString(list), new TypeReference<List<UserVO>>() {
//        });
//        if (userVOS!=null&&userVOS.size()>0){
//            UserVO userVO = userVOS.get(0);
//            return JsonResult.success(userVO);
//        }
//       return JsonResult.fail();
        UserAuthVO userAuthVO = userService.getByUserOrNickName(name);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userAuthVO, userVO);
        return JsonResult.success(userVO);
    }


    /**
     * 下载用户数据录入excel模板
     */
    @ApiOperation(value = "下载用户数据录入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"企业(*)", "用户名(工号)(*)", "姓名(*)", "性别(*)", "部门(*)", "岗位(*)", "职务(*)", "学历", "身份证号码(*)", "出生年月(*)", "家庭住址(*)", "联系电话(*)", "入职时间(*)", "养老保险", "医疗保险", "工伤保险", "失业保险", "衣服尺码", "鞋子尺码", "合同开始时间", "合同结束时间"};
        List<String[]> downData = new ArrayList<>();
        List<String> indexArr = new ArrayList<>();
        StringBuffer tempStr = new StringBuffer();
        //企业列表
        List<CompanyInfo> list1 = companyInfoService.list();
        String[] data = new String[list1.size()];
        for (int i = 0; i < list1.size(); i++) {
            data[i] = list1.get(i).getName();
        }
        indexArr.add("0");
        downData.add(data);
        //性别
        String[] sexData = new String[]{"男", "女"};
        indexArr.add("3");
        downData.add(sexData);
        //部门
        QueryWrapper<Role> departmentQueryWrapper = new QueryWrapper<>();
        departmentQueryWrapper.eq("is_produce", 1);
        List<Role> departmentList = roleService.list(departmentQueryWrapper);
        String[] departmentData = new String[departmentList.size()];
        for (int i = 0; i < departmentList.size(); i++) {
            departmentData[i] = departmentList.get(i).getName();
        }
        indexArr.add("4");
        downData.add(departmentData);
        //岗位
        QueryWrapper<Role> jobQueryWrapper = new QueryWrapper<>();
        jobQueryWrapper.eq("is_produce", 0);
        List<Role> jobList = roleService.list(jobQueryWrapper);
        String[] jobData = new String[jobList.size()];
        for (int i = 0; i < jobList.size(); i++) {
            jobData[i] = jobList.get(i).getName();
        }
        indexArr.add("5");
        downData.add(jobData);
        //职务
        QueryWrapper<Position> positionQueryWrapper = new QueryWrapper<>();
        List<Position> positionList = positionService.list(positionQueryWrapper);
        String[] positionData = new String[positionList.size()];
        for (int i = 0; i < positionList.size(); i++) {
            positionData[i] = positionList.get(i).getName();
        }
        indexArr.add("6");
        downData.add(positionData);

        DownExcelUtil.createExcelTemplate(response, request, "用户导入模板", Arrays.asList(headerArr), downData, indexArr);
    }

    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<UserExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<UserExcelIn> list = reader.read(is, UserExcelIn.class);
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            userService.importExcel(list);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }

    @ApiOperation(value = "导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        List<Map<String, Object>> headerList = new ArrayList<>();
        Map<String, Object> headParams = new HashMap();
        headParams.put("username", "用户名(工号)");
        headParams.put("nickname", "姓名");
        headParams.put("phone", "手机号");
        headParams.put("sex", "性别");
        //headParams.put("idCard", "身份证号");
        headParams.put("companyInfoName", "企业");
        headParams.put("departmentName", "部门");
        headParams.put("roleName", "岗位");
        headerList.add(headParams);
        Map<String, Object> params = new HashMap();
        List<UserExcelIn> list = userService.exportList(params);
        ExcelUtils.export(response, "用户", list, UserExcelIn.class, headerList);
    }

    /**
     * 同步东江用户数据
     *
     * @return
     */
    @PostMapping("/syncDjUserInfo")
    public JsonResult syncDjUserInfo() {
        userService.syncDjUserInfo();
        return JsonResult.success();
    }

    @ApiOperation(value = "按成本中心统计人数", notes = "搜索")
    @GetMapping("/costCenterBodyCount")
    public JsonResult costCenterBodyCount(@RequestParam("type") String type//012 当日当周当月
            , @RequestParam("startTime") String startTime//时间搜索 开始时间
            , @RequestParam("endTime") String endTime//时间搜索 结束时间
            , @RequestParam("param") String param //柱状图饼状图的下拉选 不同的选项 qua 数量 money 金额
            , @RequestParam("costCenter") String costCenter //成本中心选择
    ) {
        return userService.costCenterBodyCount(type, startTime, endTime, param, JwtUtils.getEnterpriseId(), costCenter);
    }

    @GetMapping("/getUserByUserName")
    public JsonResult<User> getUserByUserName(String username) {
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        return JsonResult.success(user);
    }

    @GetMapping("/getUserInfoByUserName")
    public JsonResult<UserVO> getUserInfoByUserName(String username) {
        UserVO user = userService.getUserInfoByUserName(username);
        return JsonResult.success(user);
    }

    @GetMapping("/passwordEncoder")
    public JsonResult passwordEncoder(String password) {
        String encode = passwordEncoder.encode(DigestUtil.md5Hex(password));
        return JsonResult.success(encode);
    }


    /**
     * 导入EXCEL信息
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcelUser")
    public JsonResult importExcelUser(HttpServletRequest request, @RequestParam("file") MultipartFile file, @RequestParam("companyNameInfo") String companyNameInfo) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            ExcelUtil<UserInfoExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<UserInfoExcelIn> read = reader.read(is, UserInfoExcelIn.class);
            if (CollectionUtils.isEmpty(read)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            userService.importExcelUser(read, companyNameInfo);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }


    @Autowired
    private MessageService messageService;

    @GetMapping("/message/send")
    public AppMessageSendResp sentMessage(String mobile, Integer agentid) {
        return messageService.sentMessage(mobile, agentid);
    }

    @ApiOperation(value = "添加第三方用户", notes = "添加第三方用户")
    @PostMapping("/addThirdUser")
    public JsonResult addThirdUser(@RequestBody User user) {
        try {
            user.setStatus(1);
            userService.addThirdUser(user);
            return JsonResult.success("添加成功");
        } catch (BusinessException e) {
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "修改第三方用户", notes = "修改第三方用户")
    @PutMapping("/updateThirdUser")
    public JsonResult updateThirdUser(@RequestBody User user) {
        try {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("phone", user.getOldPhone());
            User user0 = userService.getOne(userQueryWrapper);
            if (user0 == null) {
                throw new BusinessException("用户不存在");
            }
            user0.setNickname(user.getNickname());
            user0.setUsername(user.getUsername());
            user0.setPhone(user.getPhone());
            userService.updateById(user0);
            return JsonResult.success("修改成功");
        } catch (BusinessException e) {
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "删除第三方用户", notes = "删除第三方用户")
    @GetMapping("/delThirdUser")
    public JsonResult delThirdUser(@RequestParam(name = "username") String username) {
        try {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("username", username);
            User user0 = userService.getOne(userQueryWrapper);
            if (user0 == null) {
                throw new BusinessException("用户名不存在");
            }
            userService.delete(user0.getId());
            return JsonResult.success("删除成功");
        } catch (BusinessException e) {
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return JsonResult.fail(e.getMessage());
        }
    }


    @GetMapping("/syncDingUserToSysUer")
    public void syncDingUserToSysUer() throws Exception {
        userService.syncDingUserToSysUer();
    }


    @GetMapping("/getUserDingConfigInfo")
    public SystemDingTalkInfo getUserDingConfigInfo() {
        return userService.getUserDingConfigInfo();
    }

    @GetMapping("/selUserDingInfo")
    public List<User> selUserDingInfo() {
        return userService.selUserDingInfo();
    }


    @Resource
    FaceRecognitionService faceRecognitionService;

    /**
     * 人脸搜索
     */
    @GetMapping("/searchFace")
    public JsonResult searchFace(String image) {
        EnterpriseInfoVO enterpriseInfoVO = faceRecognitionService.getEnterpriseInfo();
        String [] groupIds = {enterpriseInfoVO.getEnterpriseId()};
        return faceRecognitionService.searchFaces(groupIds,image);
    }
}
